<?php

// No direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.controller');

class ApkipasController extends JController
{

	public function display($cachable = false, $urlparams = false)
	{
		$cachable = true;

		// Get the document object.
		$document = JFactory::getDocument();

		// Set the default view name and format from the Request.
		$vName		= JRequest::getCmd('view', 'apkias');
		JRequest::setVar('view', $vName);

		$user = JFactory::getUser();

		$safeurlparams = array('id'=>'INT','tag'=>'STRING');

		parent::display($cachable, $safeurlparams);

		return $this;
	}
	
	function apkipas(){
		$app = &JFactory::getApplication();
		$id = &JRequest::getVar('id');
		$db = &JFactory::getDbo();
		
		$query = 'SELECT a.id,a.alias FROM #__apkipas_titles as a
		LEFT JOIN #__apkipas_resources as b
		ON a.product_id = b.id WHERE b.itune_id = '.$id.' ORDER BY a.id DESC LIMIT 1';
		
		$db->setQuery($query);
		$rs = $db->loadObject();
		
		$link = JRoute::_('index.php?option=com_apkipas&view=detail&id='.$rs->id.':'.$rs->alias.'&Itemid=107');
		$app->redirect($link);
	}
	
	function addLink() {
		$user = JFactory::getUser();
		$itemid = JRequest::getVar('itemid');
		$link = JRequest::getVar('link');
		
		$db = JFactory::getDBO();
		$datenow = &JFactory::getDate();

        $arr = array('http://','www.');
        $source = str_ireplace($arr, '', $link);
        $sourcearr = explode('/', $source);
        
		$linkdetail = new stdClass();
		$linkdetail->id = null;
		$linkdetail->download_id = $itemid;
		$linkdetail->link = $link;
		$linkdetail->source = $sourcearr[0];
		$linkdetail->status = 1;
		$linkdetail->created_date = $datenow->toMySQL();
		$linkdetail->author = $user->id;

		//update item link
		$query = 'UPDATE #__apkipas_titles SET modified_date = "'.$datenow->toMySQL().'" WHERE id = '.$itemid;
		$db->setQuery($query);
		$db->query();
        
		$app = $this->getVesrionApps($itemid);
		$ituneobj = new stdClass();
		$ituneobj->id = null;
		$ituneobj->version = $app->version;
		$ituneobj->itune_id = $app->itune_id;
		$ituneobj->source = $sourcearr[0];
		$ituneobj->link = $link;
		$ituneobj->author = $user->id;
		$ituneobj->report = 0;
		$ituneobj->created_date = $datenow->toMySQL();
		$ituneobj->published = 1;
		$ituneobj->type = 'manual';
		$ituneobj->date_check = '';
		
		$db->insertObject('#__apkipas_itunedownload', $ituneobj);
		if($db->insertObject('#__apkipas_download_detail', $linkdetail))
			echo 1;
		else
			echo 0;
		jexit();
	}
	
	function getVesrionApps($id){
		$db = JFactory::getDbo();
		$query = 'select a.version , b.itune_id FROM #__apkipas_downloads as a 
					left join #__apkipas_resources as b oN a.product_id = b.id
					where a.id = '.$id;
		$db->setQuery($query);
		return $db->loadObject();
	}
}
